package ActivityPractice;

/**
 * Created by 蜡笔小新丶 on 2017/10/9.
 */

public class ArrayStack<T> implements Stack<T>
{
    private final int DEFAULT_CAPACITY = 100;
    private int num;
    private T[] stack;
    public ArrayStack()
    {
        num = 0;
        stack = (T[])(new Object[DEFAULT_CAPACITY]);
    }

    public ArrayStack (int lenth)
    {
        num = 0;
        stack = (T[])(new Object[lenth]);
    }

    public void push (T element)
    {
        if (size() == stack.length)
            expandCapacity();

        stack[num] = element;
        num++;
    }

    public T pop() throws Exception
    {
        if (isEmpty())
            throw new Exception("Stack is empty");

        num--;
        T result = stack[num];
        stack[num] = null;

        return result;
    }

    public T peek() throws Exception
    {
        if (isEmpty())
            throw new Exception("Stack is empty");

        return stack[num -1];
    }


    public boolean isEmpty()
    {
        return (num == 0);
    }

    public int size()
    {
        return num;
    }

    public String toString()
    {
        String result = "";

        for (int scan = 0; scan < num; scan++)
            result = result + stack[scan].toString() + "\n";

        return result;
    }

    private void expandCapacity()
    {
        T[] larger = (T[])(new Object[stack.length*2]);

        for (int index=0; index < stack.length; index++)
            larger[index] = stack[index];

        stack = larger;
    }
}


